package com.ton.task.tron;
import com.ton.context.RedisContext;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;
import com.ton.common.entity.Transaction;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Date;
import java.util.Objects;

/**
 * 监听账户交易记录
 */
@Component
@Slf4j
//QuartzJobBean
public class TransactionListener extends QuartzJobBean {
    //查找所有的trx转账情况

    //官方的api 见 https://docs.tronscan.org/api-endpoints/transactions-and-transfers
    //测试服务的APi
    private String TRXURL = "https://apilist.tronscanapi.com/api/transfer?sort=-timestamp&count=true&limit=30&start=0&filterTokenValue=0&address=";

    //b91990d47a289b8524706ea0578f559d3f08bd0f7de02df4956075e66503f048
    private String GameAccount = "TDVbYKBu5kY8BmxWvzmYizswf8UVJLy2mN";
    private String GamePrivateKey = "";
    private String ToAccount = "TDVbYKBu5kY8BmxWvzmYizswf8UVJLy2mN";

//    @Autowired
//    private TransactionService transactionService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private RedisContext redisContext;

    /**
     * 监听 账户转账记录 -- 需要传递一个Account
     * @param context 包装对象
     * @throws JobExecutionException 异常拦截
     */
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap(); //获取参数详情对象
        String targetAddress= (String)jobDataMap.get("targetAddress");
        StringBuilder trxstr = new StringBuilder();
        trxstr.append(TRXURL).append(targetAddress);

        try {
            HttpClient client = HttpClients.createDefault();
            HttpGet request = new HttpGet(trxstr.toString());
            //
            request.addHeader("TRON-PRO-API-KEY", "61c7495c-eb99-46df-a1c7-e3c25aae1ece");
            //request.addHeader("TRON-PRO-API-KEY", "fac9fa5c-ec1e-4373-b524-fc4f2166bf32");
            BufferedReader reader = new BufferedReader(new InputStreamReader(client.execute(request).getEntity().getContent()));
            StringBuilder responseBody = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null)
                responseBody.append(line);

            reader.close();
            dealtrx(responseBody.toString(), targetAddress);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void dealtrx(String urlResult, String toAddress) {
        try {
            System.out.println("---->"+urlResult.trim());
            System.out.println("trx result:  " + toAddress + ":" + urlResult.trim().substring(0, 10));
            if (urlResult.trim().contains("Exceed")) {
                return;
            }
            JSONObject json1 = new JSONObject(urlResult.trim());
            if (json1.has("data")) {
                JSONArray json = json1.getJSONArray("data");
                for (int j = 0; j < json.length(); j++) {
                     String txHash=null;
                    Transaction transaction = new Transaction();
                    String abbr = "";
                    BigInteger amount = new BigInteger("0");

                    //定义数据库去存储
                    JSONObject json2 = (JSONObject) json.get(j);
                    if (json2.has("transactionHash")) {
                        txHash = json2.getString("transactionHash");

                        //判断redis内有无key
                        String hashKey = redisContext.getTransactionHashKey(txHash);
                        Object o = redisTemplate.opsForValue().get(hashKey);
                        if(Objects.nonNull(o)){
                            hashKey=null;
                            continue;
                        }

//                        LambdaQueryWrapper<Transaction> wrapper=new LambdaQueryWrapper<>();
//                        wrapper.eq(Transaction::getHash,txHash);
//                        long count = transactionService.count(wrapper);
//                        //存储到数据库检查是否已经存在交易了如果存在改交易就直接跳过，因为整个交易是从尾部往前边遍历的。
//                        //已经有交易了就跳过
//                        if(count>0){
//                            continue;
//                        }
                        //在这里设置交易哈希
                        transaction.setHash(txHash);
                        //System.out.println("hash:" + txHash);
                    }
                    if (json2.has("block")) {
                        transaction.setBlock(json2.getLong("block"));
                    }
                    if (json2.has("timestamp")) {
                        long timeStamp = json2.getLong("timestamp");
                        Date dateFormat = new Date(timeStamp);
                        transaction.setTimeStamp(dateFormat);
                    }
                    if (json2.has("transferFromAddress")) {
                        transaction.setFromAddress(json2.getString("transferFromAddress"));;
                    }
                    if (json2.has("transferToAddress")) {
                        transaction.setToAddress(json2.getString("transferToAddress"));;
                    }
                    if (json2.has("tokenInfo")) {
                        JSONObject tokenInfo = json2.getJSONObject("tokenInfo");
                        if (tokenInfo.has("tokenId")) {
                        }
                        if (tokenInfo.has("tokenAbbr")) {
                            //如果不是trx交易则跳过
                            if (!tokenInfo.getString("tokenAbbr").equals("trx")) {
                                continue;
                            }
                            abbr = tokenInfo.getString("tokenAbbr");
                            String tokenAbbr = tokenInfo.getString("tokenAbbr");
                            if(tokenAbbr.equals("trx")){
                                transaction.setCoinType(0);
                            }
                            if(tokenAbbr.equals("trc")){
                                transaction.setCoinType(1);
                            }
                        }
                        if (tokenInfo.has("tokenName")) {
                            transaction.setTokenName(tokenInfo.getString("tokenName")); //设置tokenName
                        }
                        if (tokenInfo.has("tokenDecimal")) {
                        }
                        if (tokenInfo.has("tokenType")) {
                            transaction.setTokenType(tokenInfo.getString("tokenType"));
                        }
                    }
                    if (json2.has("amount")) {
                        amount = new BigInteger(String.valueOf(json2.getInt("amount")));
                        transaction.setAmount(amount);
                    }
                    if (json2.has("confirmed")) {
                        if(json2.getBoolean("confirmed")){
                           transaction.setIsConfirm(1);
                        }else{
                           transaction.setIsConfirm(0);
                        }

                    }
                    if (json2.has("contractRet")) {
                        transaction.setContractRet(json2.getString("contractRet")); //设置交易结果
                    }
//                    boolean save = transactionService.save(transaction);
//                    if(save){
//                        System.out.println("保存成功!");
//                    }
                    if(Objects.nonNull(txHash)){
                        redisTemplate.opsForValue().set(redisContext.getTransactionHashKey(txHash),transaction);
                        //判断这一笔新的交易是不是我们账户的交易
                        String address = redisContext.getCreateAddress(transaction.getFromAddress());
                        Object o = redisTemplate.opsForValue().get(address);
                        if(Objects.isNull(o)){
                            if(transaction.getToAddress().equals("TDVbYKBu5kY8BmxWvzmYizswf8UVJLy2mN") && transaction.getAmount().compareTo(new BigInteger("100"))>0){
                                System.out.println("============发现交易===========");
                                System.out.println(transaction.getFromAddress()+"向你转账："+transaction.getAmount());
                            }
                        }
                    }

                    if (json2.has("transactionHash")) {
                        if (abbr.equals("trx")) {
                            if (amount.longValue() != 0) {
                                //TODO:转账到另外的账户然后做别的处理
//                                String txid1 = tronUtils.sendTRXTransaction(GameAccount,GamePrivateKey,ToAccount,amount.longValue());
//                                if(txid1!=null){
//                                    System.out.println("转账到另外的账户成功");
//                                }
                            }
                        }
                    }
                    //System.out.println("================================交易结束====================================");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString());
        }
    }
}
